package cn.nexd.app.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by xun on 2016/5/16.
 * 自定义邮箱匹配器
 */
public class AutoEmailEditText extends AutoCompleteTextView {
    private ArrayList<String> emailAddress = new ArrayList<String>();

    public AutoEmailEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        emailAddress.add("@nexdtech.com");
        init(context);
    }

    private void init(final Context context) {
        final EmailAdapter emailAdapter = new EmailAdapter(context);
        setThreshold(1);
        setAdapter(emailAdapter);
        addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                String input = s.toString();
                emailAdapter.mList.clear();
                if (!TextUtils.isEmpty(input)) {
                    if (input.contains("@")) {
                        String matched = "@";
                        String email = input;
                        String[] stringArry = input.toString().split("@");
                        try {
                            email = stringArry[0];
                            matched += stringArry[1];
                        } catch (ArrayIndexOutOfBoundsException aioobE) {

                        } finally {
                            matched = matched.toLowerCase();
                        }
                        if (!email.matches("^[A-Za-z0-9]+$")) {
                            Toast.makeText(context, "您输入的邮箱名称不符合格式", Toast.LENGTH_SHORT);
                            return;
                        }
                        for (String item : emailAddress) {
                            final String value = item;
                            final String valueText = value.toLowerCase();
                            if (valueText.startsWith(matched)) {
                                emailAdapter.mList.add(email + value);
                            }
                        }
                    }
                    emailAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }
        });
    }


    class EmailAdapter extends BaseAdapter implements Filterable {
        ArrayList<String> mList;
        Context mContext;
        EmailFilter mEmailFilter;

        public EmailAdapter(Context context) {
            mContext = context;
            mList = new ArrayList<String>();
        }


        @Override
        public int getCount() {
            return mList.size() == 0 ? 0 : mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(android.R.layout.select_dialog_item, null);
                ((TextView) convertView).setText(mList.get(position));
            } else {
                ((TextView) convertView).setText(mList.get(position));
            }
            return convertView;
        }

        @Override
        public Filter getFilter() {
            if (mEmailFilter == null) {
                mEmailFilter = new EmailFilter();
            }
            return mEmailFilter;
        }

        private class EmailFilter extends Filter {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (mList == null) {
                    mList = new ArrayList<String>();
                }
                results.values = mList;
                results.count = mList.size();
                return results;
            }


            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results.count != 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }

            }
        }
    }

}
